#pragma once 

#include <iostream>
#include <memory>
#include <unordered_map>
#include "Epoller.hpp"
#include "Connection.hpp"

using namespace EpollModule;
using connection_t = std::shared_ptr<Connection>;

class Reactor
{
    const static int event_num = 64;
private:
    bool IsConnectionExists(int sockfd)
    {
        return _connections.find(sockfd) == _connections.end();
    }
public:
    Reactor():_isrunning(false),_epoller(std::make_unique<Epoller>())
    {
        _epoller->Init();
    }
    void InsertConnection(connection_t conn)
    {
        auto iter = _connections.find(conn->sockfd());
        if(iter == _connections.end())
        {
            //1.将链接放到unordered_map中
            _connections.insert(std::make_pair(conn->sockfd(),conn));
            //2.插入的链接写入epoll中
            _epoller->Add(conn->sockfd(),conn->GetEvents());
            //3.设置管理关心,让connection回指当前对象
            conn->SetOwner(this);
            LOG(LogLevel::DEBUG) << "add connection success: " << conn->sockfd();
        }
    }

    void DelConnection(int sockfd)
    {
        if(IsConnectionExists(sockfd))
        {
            //1.从内核先移除
            _epoller->Delete(sockfd);
            //2.关闭特定的文件描述符
            _connections[sockfd]->Close();
            //3.从_connections中移除对于的connection
            _connections.erase(sockfd);
        }
    }

    void EnableReadWrite(int sockfd,bool readable,bool writeable)
    {
        if(IsConnectionExists(sockfd))
        {
            uint32_t events = (readable ? EPOLLIN : 0) | (writeable ? EPOLLOUT : 0) | EPOLLET;
           _connections[sockfd]->SetEvents(events);

           _epoller->Update(sockfd,_connections[sockfd]->GetEvents());
        }
    }


    // 基于事件驱动的事件派发器
    void Dispatcher(int n)
    {
        for(int i = 0;i < n;i++)
        {
            //开始派发任务
            int sockfd = _revs[i].data.fd;
            uint32_t revents = _revs[i].events;
            if((revents & EPOLLERR) || (revents & EPOLLHUP))
            {
                revents = (EPOLLIN | EPOLLOUT);//异常事件转换成为读写事件
            }
            if((revents & EPOLLIN) && IsConnectionExists(sockfd))
            {
                _connections[sockfd]->Recver();
            }
            if((revents & EPOLLOUT) && IsConnectionExists(sockfd))
            {
                _connections[sockfd]->Sender();
            }
        }
    }
    void LoopOnce(int timeout)
    {
        int n = _epoller->Wait(_revs,event_num,timeout);
        Dispatcher(n);
    }
    void DebugPrint()
    {
        std::cout << "Epoller 管理的fd: ";
        for(auto& iter : _connections)
        {
            std::cout << iter.first << " ";
        }
        std::cout << std::endl;
    }
    void Loop()
    {
        _isrunning = true;
        int timeout = -1;
        while(_isrunning)
        {
            LoopOnce(timeout);
            //后续我们可以在这里进行超时管理
            DebugPrint();
        }
        _isrunning = false;
    }
    void Stop()
    {
        _isrunning = false;
    }
    ~Reactor()
    {

    }
private:
    std::unique_ptr<Epoller> _epoller;
    std::unordered_map<int,connection_t> _connections; //服务器内部所有的链接
    bool _isrunning;
    struct epoll_event _revs[event_num];
};

